package com.master.service;


import com.master.domain.MiaoshaOrder;
import com.master.domain.MiaoshaUser;
import com.master.domain.OrderInfo;
import com.master.redis.MiaoshaKey;
import com.master.redis.RedisServer;
import com.master.util.MD5Util;
import com.master.util.UUIDUtil;
import com.master.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;


@Service
public class MiaoshaService {

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    RedisServer redisServer;

    @Transactional
    public OrderInfo miaosha(MiaoshaUser user, GoodsVo goodsVo) {
        //减少库存,更新库存
        boolean success = goodsService.reduceStock(goodsVo);

        OrderInfo orderInfo = null;
        if(success) {
            //下订单
            orderInfo = orderService.createOrder(user,goodsVo);
        }else{
            setGoodsOver(goodsVo.getId());
            return null;
        }
        return orderInfo;

    }

    //查询用户是否秒杀成功
    //获取秒杀结果
    public long getMiaoshaResult(Long userId, long goodsId) {
        //从缓存中查询秒杀订单是否已经存在
        //就是从缓存中判断秒杀是否已经成功
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(userId,goodsId);
        if(order != null){//说明秒杀成功,返回订单id
            return order.getOrderId();
        }else{
            //有两种情况
            //(1)秒杀失败(2)还在排队中
            boolean isOver = getGoodsOver(goodsId);
            if(isOver){
                //商品已经秒杀完了
                return -1;
            }else{
                //商品没有卖完,秒杀订单也没有生成
                return 0;
            }
        }
    }

    private boolean getGoodsOver(long goodsId) {
        //判断redis中是否有这个key,如果有则表示商品已经秒杀完了
       return redisServer.exists(MiaoshaKey.isGoodsOver,""+goodsId);
    }

    public void setGoodsOver(Long goodsId) {
        redisServer.set(MiaoshaKey.isGoodsOver,""+goodsId,true);
    }

    public boolean checkPath(String path,MiaoshaUser user,long goodsId){
        if(user == null || path == null){
            return false;
        }

        //从redis中判断两个path是否相等
        String pathOld = redisServer.get(MiaoshaKey.getMiaoshaPath,""+user.getId()+"_"+goodsId,String.class);
        return path.equals(pathOld);
    }


    public String createMiaoshaPath(MiaoshaUser user,long goodsId) {
        String str = MD5Util.md5(UUIDUtil.uuid()+"123456");
        //然后需要把这个path保存到redis中,因为客户端之后的请求要带上这个随机的path
        redisServer.set(MiaoshaKey.getMiaoshaPath,""+user.getId()+"_"+goodsId,str);
        return str;
    }

    //生成图形验证码
    public BufferedImage createMiaoshaVerifyCode(MiaoshaUser user, long goodsId) {
        if(user == null || goodsId <= 0){
            return null;
        }

        int width = 80;
        int height = 32;
        //创建了BufferedImage的图像,内存中的图像
        BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        // set the background color
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        // draw the border
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);
        // create a random instance to generate the codes
        Random rdm = new Random();
        // make some confusion
        for (int i = 0; i < 50; i++) {
            int x = rdm.nextInt(width);
            int y = rdm.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }
        // 生成验证码
        String verifyCode = generateVerifyCode(rdm);
        g.setColor(new Color(0, 100, 0));
        g.setFont(new Font("Candara", Font.BOLD, 24));
        //把验证码写到图片上
        g.drawString(verifyCode, 8, 24);
        g.dispose();
        //把验证码存到redis中
        int rnd = calc(verifyCode);
        redisServer.set(MiaoshaKey.getMiaoshaVerifyCode, user.getId()+","+goodsId, rnd);
        //输出图片
        return image;
    }

    //计算表达式结果
    private int calc(String verifyCode) {
        try{
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            return (int)engine.eval(verifyCode);

        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }


    private static char[] ops = new char[]{'+','-','*'};
    //生成验证码
    //只做+ - *
    private String generateVerifyCode(Random rdm) {
        int num1 = rdm.nextInt(10);
        int num2 = rdm.nextInt(10);
        int num3 = rdm.nextInt(10);
        char op1 = ops[rdm.nextInt(3)];
        char op2 = ops[rdm.nextInt(3)];
        String exp = "" + num1 + op1 + num2 + op2 + num3;
        return exp;
    }


    //对用户输入的验证码进行校验
    public boolean checkVerifyCode(MiaoshaUser user, long goodsId, int verifyCode) {
        if(user == null || goodsId <= 0){
            return false;
        }
        Integer codeOld = redisServer.get(MiaoshaKey.getMiaoshaVerifyCode,user.getId()+","+goodsId,Integer.class);
        if(codeOld == null || codeOld - verifyCode != 0){
            return false;
        }
        //从redis中将缓存的验证码删除
        redisServer.decr(MiaoshaKey.getMiaoshaVerifyCode,user.getId()+","+goodsId);
        return true;
    }
}
